/**
 * Created by ZT on 2018/10/9 0009.
 */

const sqls = require('../sqlMap');  //对应的mysql语句
const query = require('../db');
const mysql = require('mysql');

/**    
 *   前 台 留 言
 *      getMessage    获取所有留言 
 *      postMessage   留言
*/


/*获取留言信息*/
exports.getMessage=(req,res,next)=>{
    let params = req.query;
    let sqlParamsEntity = [];
    let page = params['page'];
    let per_page = params['per_page'];
    let where = `INNER JOIN zt_user AS B ON B.id = A.userId WHERE A.type = 0 AND A.r_id = 0`;
    let fields = `A.content,B.username,A.date,A.userId,A.r_id`;
    let sql5 = sqls.coTableData('zt_discuss', where, fields, page, per_page);
    console.log(sql5);
    var where6 = `left JOIN zt_user as B on B.id = A.userId where A.type=0`;
    let sql6 = sqls.coTableData('zt_discuss', where6, fields, page = 1, per_page = 5);
    sqlParamsEntity.push(query.getNewSqlParamEntity(sql5, {}));
    sqlParamsEntity.push(query.getNewSqlParamEntity(sql6, {}));
    query.execTrans(sqlParamsEntity, function (err, result) {
        console.log(result, 78);
        if (err) {
            console.error("事务执行失败");
        } else {
            let params = {};
            params['message'] = result[0];
            params['user'] = result[1];
            let results = { 'ret': 1, 'rows': params };
            res.send(results);
        }
    });
}

exports.postMessage=(req,res,next)=>{
    var sqlParamsEntity = [];
    var sql = sqls.findData('zt_user', `where username='${req.body.username}'`);
    sqlParamsEntity.push(query.getNewSqlParamEntity(sql, {}));
    query.execTrans(sqlParamsEntity, function (err, result) {
        if (err) {
            console.error("事务执行失败");
        } else {
            if (result[0].length > 0) {
                var sqlParamsEntity = [];
                var eachValue = [];
                var feild = 'content,date,userId,r_id,type';
                eachValue.push(req.body.content); //内容id
                eachValue.push(new Date().Format()); //标题
                eachValue.push(result[0][0]['id']); //副标题
                eachValue.push(req.body.userId);  // 概要
                eachValue.push(0);  // 概要
                let insetContent = sqls.insertTable('zt_discuss', feild, '?,?,?,?,?');
                let sqls2 = mysql.format(insetContent,eachValue);
                query.connect(sqls2, function (err, result1) {
                    if (err) {
                        console.error("事务执行失败");
                    } else {
                        var results = { 'ret': 1 };
                        res.send(results);
                    }
                });
            } else {
                var feild = 'username,email,ip';
                var eachValue = [];
                var sqlParamsEntity = [];
                eachValue.push(req.body.username); //内容id
                eachValue.push(req.body.email); //标题
                eachValue.push(query.getIp(req));
                var insetContent = sqls.insertTable('zt_user', feild, eachValue);
                var find = sqls.findLatId('zt_user');
                sqlParamsEntity.push(query.getNewSqlParamEntity(insetContent, {}));
                sqlParamsEntity.push(query.getNewSqlParamEntity(find, {}));
                query.execTrans(sqlParamsEntity, function (err, result1) {
                    if (err) {
                        console.error("事务执行失败");
                    } else {
                        let lastId = result1[1]['LAST_INSERT_ID()'];
                        let eachValue1 = [];
                        let feild = 'content,date,userId,r_id,type';
                        eachValue1.push(req.body.content); //内容id
                        eachValue1.push(new Date().Format()); //标题
                        eachValue1.push(lastId); //副标题
                        eachValue1.push(req.body.userId);  // 概要
                        eachValue1.push(0);  // 概要
                        let insetContent = sqls.insertTable('zt_discuss', feild, '?,?,?,?,?');
                        let sqls2 = mysql.format(insetContent,eachValue1);
                        query.connect(sqls2, function (err, result1) {
                            if (err) {
                                console.error("事务执行失败");
                            } else {
                                var results = { 'ret': 1 };
                                res.send(results);
                            }
                        });
                    }
                })
            }
        }
    });
}


/////获取前台某篇文章的留言
exports.getArticleInfoMessage =(req,res,next)=> {
    // type 0,1,2  留言，文章留言  照片留言
    let param = req.query;
    let union = `left join zt_user as B on A.userId=B.id where A.article_id = ${param.id}`;
    let filed = `A.content,A.date,B.username`;
    let sql = sqls.coTableData(`zt_discuss_article`, union, filed, param.page, param.per_page);
    let sql1 =sqls.findData('zt_user',`where ip = '${query.getIp(req)}'`);
    let sqlParamsEntity =[];
    sqlParamsEntity.push(query.getNewSqlParamEntity(sql, {}));
    sqlParamsEntity.push(query.getNewSqlParamEntity(sql1, {}));
    query.execTrans(sqlParamsEntity, function (err, result) {
        if (err) {
            console.error("事务执行失败");
        } else {
            let results = {'ret': 1, 'rows': result[0],'user':result[1]};
            res.send(results);
        }
    });
}
exports.postArticleInfoMessage=(req,res,next)=>{
    let params = req.body;
    let field   = `article_id,content,userId,r_id,date`;
    let value =`${params.article_id},'${params.content}','${params.userId}',0,'${new Date().Format()}'`;
    let sql = sqls.insertTable('zt_discuss_article',field,value);
    console.log(sql,333);
    query.connect(sql,function (err,result) {
        if (err) {
            console.error("事务执行失败");
        } else {
            var results = { 'ret': 1 };
            res.send(results);
        }
    })
}